var pageBean = null;
var dataList = {};
var provinces = {};
var cities = {};
var spaces = {};
var productTypes = {};
var processPersons = {};
var salesPersons = {};
var sourceOfChannels = {};
var currentData = null;
var extensions = {};
var clientClassifications = {};

$(document).ready(function(e) {	
	
	$('#newClueFollow').click(function(){ //打开添加跟进记录窗口
        $('.theme-popover-mask').fadeIn(100);  
        $('#clueFollowForm').slideDown(200);  
        clearClueFollowForm();
    })  
    $('#closeClueFollow').click(closeClueFollow);//添加跟进记录窗口右上角的关闭
	$('#btnCancleClueFollow').click(closeClueFollow);//添加跟进记录窗口下面的取消按钮
	$('#btnSaveClueFollow').click(saveClueFollow);//添加跟进记录下的确定按钮
    
    $('#newOrder').click(function(){ //打开添加订单窗口
        $('.theme-popover-mask').fadeIn(100);  
        $('#orderForm').slideDown(200);  
        $('#btnSaveOrder').unbind();
        $('#btnSaveOrder').click(saveOrder);//添加订单窗口下确定按钮
        if(currentData != null){
        	var mClient = currentData['client'];
        	var provinceId = $("#formProvince").val();
        	var cityId =  $("#formCity").val();
        	var spaceId = $("#formSpace").val();
        	var processPersonId = $("select[name='processPerson'][formparameter='clue']").val();        	
        	$("select[name='salesPerson'][formparameter='order']").val(processPersonId).trigger('change');        	
        	$("SELECT[name='cityId'][formParameter='order']").unbind();
        	$("SELECT[name='cityId'][formParameter='order']").val(cityId).trigger('change');        	
        	$('#salesTime222').val(laydate.now(0, 'YYYY-MM-DD'));
        	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='order']");	
        	$(spaceIdSelect).empty();
        	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
        	if(cityId == '0'){
        		$.each(spaces,function(key,space){	
        			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
        		});
        	}else{
        		$.each(spaces,function(key,space){	
        			if(cityId == space.city.cityId){
        				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
        			}
        		});
        	}
        	$(spaceIdSelect).val(spaceId).trigger('change');
        	$("SELECT[name='cityId'][formParameter='order']").change(cityIdOrderChange);
        	$("[name='orderName'][formParameter='order']").val(''); 
        	$("[name='description'][formParameter='order']").val(''); 
        }
    })  
    $('#closeOrder').click(closeOrder);//添加订单窗口右上角的关闭
    $('#btnCancleOrder').click(closeOrder);//添加订单窗口下面的取消按钮
    
    
	//切换客户类型输入信息
	$("#formClientType").change(clientTypeChange);	
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);	
	$("#btnClean").click(clean);
	$("#btnAdd").click(add);
	$("#clientExtensions").hide();
	
	$("A[name='clientDetail']").click(clientDetail);
	$("A[name='clientOrder']").click(clientOrder);
	
	initialExtensions();
	
	initialClientclassifications();
	initialPlaces();
	initialSpace();
	initialSourceOfChannel();
	initialProductType();
	search(1);
	initialSelect();
	initialProcessPerson();
	$("SELECT[name='placeProvinceSelect']").change(provinceChange);	
	$("SELECT[name='provinceId']").change(provinceIdChange);
	$("SELECT[name='placeCitySelect']").change(cityChange);
	$("SELECT[name='cityId'][formParameter='clue']").change(cityIdChange);
	$("SELECT[name='cityId'][formParameter='order']").change(cityIdOrderChange);
});

function closeClueFollow(){
	 $('.theme-popover-mask').fadeOut(100);  
     $('#clueFollowForm').slideUp(200);  
}

function clearClueFollowForm(){	
	$("[formParameter='clueFollow']").each(function(index,element){
		try{
			var name = $(element).attr("name");	
			if("clientClassification" == name){
				var firstVal = $(element).find('option').eq(0).val();				
				$(element).val(firstVal).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function saveClueFollow(){
	var clueFollow = {};
	$("[formParameter='clueFollow']").each(function(index,element){
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				clueFollow = false;
				return false;
			}
			if("clientClassification" == name){
				clueFollow[name] = clientClassifications[val];
			}else{
				clueFollow[name] = val;
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	if(currentData != null){
		clueFollow["clueId"] = currentData["id"];
	}
	if(clueFollow != false){
		$.ajax({
	        url: '/euc/clue/addfollow',
	        data:JSON.stringify(clueFollow),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType:'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	try{
	        		clueFollow = result.data; 
	        		var newFollowIndex = -1;
	        		$.each(currentData["clueFollowList"],function(index,follow){
	        			if(follow.id == clueFollow.id){
	        				newFollowIndex = index;
	        				return false;
	        			}else{
	        				newFollowIndex = index+1;
	        			}
	        		});
	        		if(newFollowIndex == -1){
	        			currentData["clueFollowList"]= [];
	        			currentData.clueFollowList[0] = clueFollow;
	        		}else{
	        			currentData.clueFollowList[newFollowIndex] = clueFollow;
	        		}
	        		setForm(currentData);
		        	closeClueFollow();
		        	clearClueFollowForm();
	        	}catch(e){
	        		console.log(e.message);
	        	}
	        },
	        error: function () {
	        	console.log(e.message);
	        }  
	    });
	}
}

function closeOrder(){
	 $('.theme-popover-mask').fadeOut(100);  
     $('#orderForm').slideUp(200);  
}

function getOrder(order){
	if(order == null){
		order = {};
	}
	$("[formParameter='order']").each(function(index,element){
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				order = false;
				return false;
			}
			if("cityId" == name){
				order[name] = val;
				order["provinceId"] = cities[val].provinceId;
			}else if("salesPerson" == name){
				order[name] = salesPersons[val];
			}else{
				order[name] = val;
			}
		}catch(e){
			console.log(e.messge);
		}
	});
//	console.log(JSON.stringify(order));
	
	if(currentData != null){
		var client = currentData["client"];
		//console.log(JSON.stringify(client));
		client = JSON.stringify(client);
		client = $.parseJSON(client);
		client["orderList"] = [];
		//console.log(JSON.stringify(client));
		order["client"] = client;
	}
	//console.log(JSON.stringify(order));
	return order;
}

function setOrder(order){
	if(order == null){
		return;
	}
	$("[formParameter='order']").each(function(index,element){
		try{					
			var name = $(element).attr("name");	
			$(element).val(order[name]);
			if("cityId" == name){
				$("select[name='"+name+"']").val(order[name]).trigger('change');				
			}else if("salesPerson" == name){
				$("select[name='"+name+"']").val(order[name].id).trigger('change');
			}else if("spaceId" == name){
				$("select[name='"+name+"']").val(order[name]).trigger('change');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function updateOrder(newOrder){
	if(newOrder == null){
		return;
	}
	newOrder = getOrder(newOrder);
	if(newOrder == false){
		return;
	}
	$.ajax({
        url: '/euc/order/update',
        data:JSON.stringify(newOrder),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		newOrder = result.data;         		
        		var newOrderIndex = -1;
        		$.each(currentData.client.orderList,function(index,order){
        			if(newOrder.id == order.id){
        				newOrderIndex = index;
        				return false;
        			}else{
        				newOrderIndex = index+1;
        			}
        		});
        		if(newOrderIndex == -1){
        			currentData.client["orderList"]= [];
        			currentData.client.orderList[0] = newOrder;
        		}else{
        			currentData.client.orderList[newOrderIndex] = newOrder;
        		}
        		setForm(currentData);
        		closeOrder();
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/order/update error");
        }  
    });
	
}

function saveOrder(){	
	var newOrder = {};
	newOrder = getOrder(newOrder);
	if(newOrder == false){
		return;
	}
	$.ajax({
        url: '/euc/order/add',
        data:JSON.stringify(newOrder),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		newOrder = result.data;         		
        		var newOrderIndex = -1;
        		$.each(currentData.client.orderList,function(index,order){
        			if(newOrder.id == order.id){
        				newOrderIndex = index;
        				return false;
        			}else{
        				newOrderIndex = index+1;
        			}
        		});
        		if(newOrderIndex == -1){
        			currentData.client["orderList"]= [];
        			currentData.client.orderList[0] = newOrder;
        		}else{
        			currentData.client.orderList[newOrderIndex] = newOrder;
        		}
        		setForm(currentData);
        		closeOrder();
        		gotoSignCustomer(result.data.id,result.data.clientName);
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/order/add error");
        }  
    });
}

function gotoSignCustomer(orderId,clientName){
	try{
		window.parent.gotoSignCustomersPage(orderId,clientName);
	}catch(e){
		console.log(e.message);
	}
}



function clientDetail(){
	$("A[name='clientDetail']").addClass("selected");
	$("A[name='clientOrder']").removeClass("selected");
	if(localStorage.getItem('isBusiManage')==='false'){
		$("#y_lingqu").hide();
	}else if(localStorage.getItem('isBusiManage')==='true'){
		$("#y_lingqu").show();
	}else{
		console.log('Exception')
	}
	$("#tab1").show();
	$("#tab2").hide();
}

function clientOrder(){
	$("A[name='clientDetail']").removeClass("selected");
	$("A[name='clientOrder']").addClass("selected");
	$("#tab1").hide();
	$("#tab2").show();
}

function initialExtensions(){
	$.ajax({
        url: '/euc/extension/list',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
	        var extensionDiv = $("#clientExtensions");
	        $(extensionDiv).empty();
	        $('<div class="formtitle "><span>企业扩展信息</span></div>').appendTo($(extensionDiv));	        
	    	$.each(result,function(i,data){
	    		var html = '';
	    		if(data.id==1){//指定所属行业
    				html += '<ul class="forminfo"  clientType="企业"><li><label >所属行业</label>';
    				html += '<select extensionId = "1" name="extension1" class="incinput"  message="请选择所属行业" formParameter="extension" >';
    				html += '<option value="请选择" selected="selected">请选择</option>';
    					html += '<option value="互联网科技">互联网科技</option>';
    					html += '<option value="贸易">贸易</option>';
    					html += '<option value="金融">金融</option>';
    					html += '<option value="电商平台">电商平台</option>';
    					html += '<option value="企业服务">企业服务</option>';
    					html += '<option value="软件开发">软件开发</option>';
    					html += '<option value="品牌设计">品牌设计</option>';
    					html += '<option value="营销推广">营销推广</option>';
    					html += '<option value="影视动漫">影视动漫</option>';
    					html += '<option value="其他">其他</option>';
    				html += '</select> </li> </ul>';
    			}else{
		    		if(data.contentLength <= 50){
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="incinput" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else if(data.contentLength <= 100){
		    			html += '<ul class="forminfo" clientType="企业">';
		    			html += '<li><label>'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="indinput" style="width:677px;" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else{
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><textarea  required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><textarea  ';
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" cols="" rows="" class="langtext"  ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '"></textarea></li></ul>'; 
		    		}
    			}
	    		$(extensionDiv).append(html);
	    		extensions[data.id] = data;
			});
	    	if(result.length > 0){
	    		$("#clientExtensions").show();
	    	}
        },
        error: function () {
        	console.log("/euc/extension/list error");
        }  
    });
}

function initialProcessPerson(){
	
	var requestJson = {functionId:'1120'};
	$.ajax({
        url: '/euc/user/functionusers',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var processPersonSelect = $("SELECT[name='processPerson']");
        	var salesPersonSelect = $("SELECT[name='salesPerson']");
        	$.each(result,function(i,data){
        		var style = '';
        		if(data.enable == 'false' || data.enable == false){
        			style = 'style="color:red;"';
        		}
        		$('<option ' + style + ' value="'+ data.id +'">'+ data.name +'</option>').appendTo($(processPersonSelect));
        		$('<option ' + style + ' value="'+ data.id +'">'+ data.name +'</option>').appendTo($(salesPersonSelect));
        		processPersons[data.id] = data;
        		salesPersons[data.id] = data;
			});
        	$(processPersonSelect).val(0).trigger('change');
        },
        error: function () {
        	console.log("/euc/user/functionusers error");
        }  
    });
	
}

function clean(){
	var provinceSelect = $("SELECT[name='placeProvinceSelect']");  
	$(provinceSelect).val(0).trigger('change');
	
	var citiesSelect = $("SELECT[name='placeCitySelect']");           		
	$.each(cities,function(key,city){	
   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
	});
	$(citiesSelect).val(0).trigger('change');
	
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$.each(spaces,function(key,space){	
   		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
	});
	$(spaceSelect).val(0).trigger('change');
	$("INPUT[name='parameter']").val('');
	$('input[name="visitTimeStart"]').val('');
	$('input[name="visitTimeEnd"]').val('');
}

function initialSelect(){
	
	var provinceSelect = $("SELECT[name='placeProvinceSelect']");
	var provinceIdSelect = $("SELECT[name='provinceId']");
	$.each(provinces, function(key, province) {//key provinceId,val province json object
		$('<option value="'+ key +'">'+ province.provinceName +'</option>').appendTo($(provinceSelect));
		$('<option value="'+ key +'">'+ province.provinceName +'</option>').appendTo($(provinceIdSelect));
	});
	
	var citiesSelect = $("SELECT[name='placeCitySelect']");  
	var cityIdClueSelect = $("SELECT[name='cityId'][formParameter='clue']");
	var cityIdOrderSelect = $("SELECT[name='cityId'][formParameter='order']");
	$.each(cities,function(key,city){	
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(cityIdClueSelect));
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(cityIdOrderSelect));
	});
	
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	var spaceIdClueSelect = $("SELECT[name='spaceId'][formParameter='clue']");
	var spaceIdOrderSelect = $("SELECT[name='spaceId'][formParameter='order']");
	$.each(spaces,function(key,space){	
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceIdClueSelect));
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceIdOrderSelect));
	});
	$(spaceSelect).val(0).trigger('change');
	$(spaceIdClueSelect).val(0).trigger('change');
	$(spaceIdOrderSelect).val(0).trigger('change');
	
	var sourceChannelIdSelect = $("SELECT[name='sourceChannelId']");	
	$.each(sourceOfChannels,function(key,sourceOfChannel){	
   		$('<option value="'+ key +'">'+ sourceOfChannel.sourceOfChannelName +'</option>').appendTo($(sourceChannelIdSelect));
	});
	$(sourceChannelIdSelect).val(0).trigger('change');
	
	
	var productTypeIdSelect = $("SELECT[name='productTypeId']");	
	$.each(productTypes,function(key,productType){	
   		$('<option value="'+ key +'">'+ productType.productTypeName +'</option>').appendTo($(productTypeIdSelect));
	});
	$(productTypeIdSelect).val(0).trigger('change');
	
	
	//初始化客户分类选择框
	var clientClassificationSelect = $("SELECT[name='clientClassification']");
	$(clientClassificationSelect).empty();
	$.each(clientClassifications, function(key, clientClassification) {//key provinceId,val province json object
		$('<option value="'+ key +'">'+ clientClassification.clientLevel.clientLevelName + "-" + clientClassification.clientClassificationName +'</option>').appendTo($(clientClassificationSelect));
		
	});
	var firstVal = $(clientClassificationSelect).find('option').eq(0).val();				
	$(clientClassificationSelect).val(firstVal).trigger('change');
}

function cityChange(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));   		
		});	
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
			}	   		
		});
	}
	$(spaceSelect).val(0).trigger('change');
}

function cityIdChange(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='clue']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
		});
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
			}	   		
		});
	}
	$(spaceIdSelect).val(0).trigger('change');
}

function cityIdOrderChange(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='order']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
		});
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
			}	   		
		});
	}
	$(spaceIdSelect).val(0).trigger('change');
}

function provinceChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var citiesSelect = $("SELECT[name='placeCitySelect']");
	$(citiesSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(citiesSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(citiesSelect));
		});
	}else{
		$.each(cities,function(key,city){	
	   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
		});
	}
	$(citiesSelect).val(0).trigger('change');
}

function provinceIdChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var cityIdSelect = $("SELECT[name='cityId'][formParameter='clue']");
	$(cityIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(cityIdSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(cityIdSelect));
		});
	}else{
		$.each(cities,function(key,city){	
	   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(cityIdSelect));
		});
	}
	$(cityIdSelect).val(0).trigger('change');
}

function initialClientclassifications(){
	try{
		var clientClassificationString = localStorage.getItem('clientClassification');
		clientClassifications = $.parseJSON(clientClassificationString);
	}catch(e){
		console.log(e.messge);
	}
}

function initialPlaces(){
	try{
		var provinceString = localStorage.getItem('province');
		var cityString = localStorage.getItem('city');
		provinces = $.parseJSON(provinceString);
		cities = $.parseJSON(cityString);
	}catch(e){
		console.log(e.messge);
	}
}

function initialSpace(){
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function initialSourceOfChannel(){
	try{
		var sourceOfChannelString = localStorage.getItem('sourceOfChannel');
		sourceOfChannels = $.parseJSON(sourceOfChannelString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/sourceofchannel',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		sourceOfChannels[data.id] = data;  
	   			});
	        	var sourceOfChannelJson = JSON.stringify(sourceOfChannels);
	        	localStorage.setItem('sourceOfChannel',sourceOfChannelJson);
        	}catch(e){
        		console.log(e.messge);
        	}
        },
        error: function () {
        	console.log('/euc/system/sourceofchannel error');
        }  
    });
}

function initialProductType(){
	try{
		var productTypeString = localStorage.getItem('productType');
		productTypes = $.parseJSON(productTypeString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/producttype',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		productTypes[data.id] = data;  
	   			});
	        	var productTypeJson = JSON.stringify(productTypes);
	        	localStorage.setItem('productType',productTypeJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function clientTypeChange(){//切换客户类型输入信息
	var clientType = $(this).children('option:selected').val();
	$("[clientType]").hide();
	$("[clientType='"+ clientType +"']").show();	
}

function getClueJson(clue){
	$("[formParameter='clue']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				clue = false;
				return false;
			}
			clue[name] = val;
		}catch(e){
			console.log(e.messge);
		}
	});
	if(clue != false){
		
		if(localStorage.getItem('isBusiManage')==='true'){
			try{
				clue['processPerson'] = processPersons[$("SELECT[name='processPerson']").val()];
			}catch(e){
				console.log(e.messge);
			}			
		}else{
			clue['processPerson'] = processPersons[localStorage.getItem('salsePerson')];
		}

		
		var client = clue['client'];
		try{
			if(client == null){
				client = {};
			}
			$("[formParameter='client']").each(function(index,element){		
				var name = $(element).attr("name");	
				client[name] = $.trim($(element).val());
			});
			clue['client'] = client;
		}catch(e){
			console.log(e.messge);
		}
		
		if(client != null && $.trim(client.clientType) != ''){
			if(client.clientType == '个人'){
				client['memberName'] = clue['contact'];
			}else if(client.clientType == '企业'){
				//client['companyName'] = clue['companyName'];
			}
		}		
		var clientExtensionList = client['clientExtensionList'];
		try{			
			if(clientExtensionList == null){
				clientExtensionList = [];
			}
			var clientType = client["clientType"];
			$("[formParameter='extension'][name^='extension']").each(function(index,element){
				if("企业" == clientType){
					var required = $(element).prop("required");
					var val =  $(element).val();
					if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
						var message = $(element).attr("message");
						alert(message);
						clue = false;
						return false;
					}
				}
				if($(element).val() == '请选择'&&"企业" == clientType){
					alert("请选择所属行业");return false;
				}
				var extensionId = $(element).attr("extensionId");
				var clientExtension = null;
				var index = -1;
				$.each(clientExtensionList,function(i,data){
					if(data.extensionId == extensionId){
						index = i;
						clientExtension = data;
					}
				});
				if(null == clientExtension){
					clientExtension = {};
				}
				clientExtension['extensionId'] = extensionId;
				clientExtension['extension'] = $(element).val();
				if(-1 == index){
					clientExtensionList[clientExtensionList.length] = clientExtension;					
				}else{
					clientExtensionList[index] = clientExtension;
				}
			});
			client['clientExtensionList'] = clientExtensionList;
		}catch(e){
			console.log(e.message);
		}
		if(false != clue){
			clue['client'] = client;
		}		
	}
	return clue;
}


function save(){
	currentData = {};
	currentData = getClueJson(currentData);
	if(currentData == false){
		return false;
	}
	$.ajax({
        url: '/euc/clue/add',
        data:JSON.stringify(currentData),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	if(datas.status == 0){        		
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	currentData = null;
            	search(pageBean.currentPage);            	
        	}else{
        		alert(datas.message);
        	}
        },
        error: function () {
        	console.log('/euc/clue/add error');
        }
    });
}

function update(currentData){
	if(currentData == null){
		return false;
	}
	currentData = getClueJson(currentData);
	if(currentData == false){
		return false;
	}
	$.ajax({
        url: '/euc/clue/update',
        data:JSON.stringify(currentData),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	if(datas.status == 0){        		
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	currentData = null;
            	search(pageBean.currentPage);            	
        	}else{
        		alert(datas.message);
        	}
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
}

function clearForm(){
	
	var provinceIdSelect = $("SELECT[name='provinceId']");  
	$(provinceIdSelect).val(0).trigger('change');
	
	var cityIdSelect = $("SELECT[name='cityId'][formParameter='clue']");  
	$(cityIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(cityIdSelect));
	$.each(cities,function(key,city){	
   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(cityIdSelect));
	});
	$(cityIdSelect).val(0).trigger('change');
	
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='clue']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));
	$.each(spaces,function(key,space){	
   		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
	});
	$(spaceIdSelect).val(0).trigger('change');
	
	$("[formParameter]").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				if("processPerson" == name){
					try{
						var currentUserId = localStorage.getItem('salsePerson');			
						$(element).val(currentUserId).trigger('change');
					}catch(e){
						console.log(e.message);
					}					
				}else{
					var firstVal = $(element).find('option').eq(0).val();				
					$(element).val(firstVal).trigger('change');
				}				
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function setForm(clue){
	$("[formParameter='clue']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				$(element).val(clue[name]).trigger('change');
			}else{
				$(element).val(clue[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	try{
		$("SELECT[name='provinceId']").val(clue['provinceId']).trigger('change');
		$("SELECT[name='cityId'][formParameter='clue']").val(clue['cityId']).trigger('change');
		$("SELECT[name='spaceId'][formParameter='clue']").val(clue['spaceId']).trigger('change');
		$("SELECT[name='processPerson']").val(clue['processPerson'].id).trigger('change');
	}catch(e){
		console.log(e.messge);
	}
	
	var client = clue['client'];
	$("[formParameter='client']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				$(element).val(client[name]).trigger('change');
			}else{
				$(element).val(client[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	
	try{
		$.each(client.clientExtensionList,function(i,data){
			$("[formParameter='extension'][name='extension"+data.extensionId+"']").val(data.extension);
		});
	}catch(e){
		console.log(e.message);
	}

	try{//设置跟进记录
		var clueFollowTable = $("#clueFollowTable");
		$(clueFollowTable).empty();
		$.each(clue.clueFollowList,function(i,clueFollow){			
			var bgcolor= localStorage.getItem('trcolor');
    		if(i % 2 == 0){
    			bgcolor = '';
    		}
			var html = '<tr '+ bgcolor +'>';
    		html += '<td>' + clueFollow.visitTime + '</td>';  
    		html += '<td>' + clueFollow.contact + '</td>';        		      		
    		html += '<td>' + clueFollow.contactNumber + '</td>';
    		html += '<td>' + clueFollow.clientClassification.clientLevel.clientLevelName + '-' + clueFollow.clientClassification.clientClassificationName + '</td>';
    		html += '<td>' + clueFollow.followUser.name + '</td>';
    		html += '<td>' + clueFollow.followContent + '</td>';
    		html += '</tr>';
        	$(clueFollowTable).append(html);
		});
	}catch(e){
		console.log(e.message);
	}
	
	
	var orderDetails = $("#orderDetailDiv");
	$(orderDetails).empty();
	try{//订单数据
		var aaa ='中华人民共和国';
		$("#noOrderDiv").show();
		$.each(clue.client.orderList,function(i,order){
			$("#noOrderDiv").hide();			
			var cityName = cities[order.cityId].cityName;
			var spaceName = spaces[order.spaceId].spaceName;			
	    	var html = 	'<div class="incForm" >';
	    	html +=  '      <div class="formtitle ">';
	    	html +=  '            <span>NO.</span>';
	    	html +=  '          <span class="iceFormTitleSpan nob" ">'+ (i+1) +'</span>';
	    	html +=  '      </div>';
	    	html +=  '      <div class="formtitle-left ">';
	    	html +=  '         <ul class="forminfo">';
	    	html +=  '             <li><label >订单编号：</label><span class="iceFormInfoSpan" ">'+ order.orderNumber +'</span></li>';
	    	html +=  '                <li><label >订单名称：</label><span class="iceFormInfoSpan" ">'+ order.orderName +'</span></li>';
	    	html +=  '                <li><label >城市：</label><span class="iceFormInfoSpan" ">'+ cityName +'</span></li>';
	    	html +=  '                <li><label >房间总数：</label><span class="iceFormInfoSpan" ">'+ order.roomCount +'</span></li>';
	    	html +=  '               <li><label >已回款金额：</label><span class="iceFormInfoSpan" ">'+ order.payAmount +'</span></li>';
	    	html +=  '               <li><label >入驻日期：</label><span class="iceFormInfoSpan" ">'+ order.enterTime +'</span></li>';
	    	html +=  '               <li><label >销售日期：</label><span class="iceFormInfoSpan" ">'+ order.salesTime +'</span></li>';
	    	html +=  '            </ul>';
	    	html +=  '        </div>';
	    	html +=  '       <div class="formtitle-right">';
	    	html +=  '            <ul class="forminfo">';
	    	html +=  '              <li><label >合同总数：</label><span class="iceFormInfoSpan" ">'+ order.contractCount +'</span></li>';
	    	html +=  '                <li><label >订单类型：</label><span class="iceFormInfoSpan" ">'+ order.orderType +'</span></li>';
	    	html +=  '              <li><label >空间：</label><span class="iceFormInfoSpan" ">'+ spaceName +'</span></li>';
	    	html +=  '             <li><label >订单总金额：</label><span class="iceFormInfoSpan" ">'+ order.orderAmount +'</span></li>';
	    	html +=  '               <li><label >未回款金额：</label><span class="iceFormInfoSpan" ">'+ order.noPayAmount +'</span></li>';
	    	html +=  '              <li><label >离场时间：</label><span class="iceFormInfoSpan" ">'+ order.leaveTime +'</span></li>';
	    	html +=  '              <li><label >销售人员：</label><span class="iceFormInfoSpan" ">'+ order.salesPerson.name +'</span></li>';
	    	html +=  '           </ul>';
	    	html +=  '       </div>';
	    	html +=  '        <div class="lingqu" style="margin-left: 190px;margin-top: 20px;" >';
	    	//html +=  '           <input name="btnOrderDetial"  type="button" orderId="'+ order.id +'" class="btn close" value="查看"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    	if(order.contractCount == 0){	    		
	    		html +=  '         <input name="btnOrderEdit"  type="button" orderId="'+ order.id +'"  class="btn close" value="编辑"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    		html +=  '         <input name="btnOrderDelete"  type="button" orderId="'+ order.id +'"  class="btn close" value="删除"/>';
	    	}
	    	html +=  '       </div>';
	    	html +=  '   </div>';
        	$(orderDetails).append(html);
		});
		$("input[type='button'][name='btnOrderEdit']").click(orderEdit);
		$("input[type='button'][name='btnOrderDelete']").click(orderDelete);
	}catch(e){
		console.log(e.message);
	}
	
}

function orderEdit(){	
	try{
		var currentOrder = null;
		var id = $(this).attr("orderId");
		$.each(currentData.client.orderList,function(index,order){
			if(order.id == id){
				currentOrder = order;
				return false;
			}
		});
		if(currentOrder != null){
			setOrder(currentOrder);
			$('.theme-popover-mask').fadeIn(100);  
	        $('#orderForm').slideDown(200);  
	        $('#btnSaveOrder').unbind();
			$('#btnSaveOrder').click(function(){
				var orderId = $(this).attr("orderId");
				$.each(currentData.client.orderList,function(index,order){
					if(order.id == orderId){
						currentOrder = order;
						return false;
					}
				});
				updateOrder(currentOrder);
			});//添加订单窗口下确定按钮		
		}		
	}catch(e){
		console.log(e.message);
	}
}

function orderDelete(){	
	if(confirm("确定删除该记录?")){
		var id = $(this).attr("orderId");
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/order/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	if(result.status == 0){	        		
	        		var orderList = [];
	        		var arrayIndex = 0;
	        		$.each(currentData.client.orderList,function(index,order){
	        			if(order.id != id){
	        				orderList[arrayIndex] = order;
	        				arrayIndex++;
	        			}
	        		});
	        		currentData.client.orderList = orderList;
	        		setForm(currentData);
	        	}else{
	        		alert(result.message);
	        	}	        	
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function add(){
	$("#operator").html("新建客户");
	clearForm();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();
	if(localStorage.getItem('isBusiManage')==='false'){
		$("#y_lingqu").hide();
	}else if(localStorage.getItem('isBusiManage')==='true'){
		$("#y_lingqu").show();
	}else{
		console.log('Exception')
	}
	$("#clueFollowDiv").hide();
	$("#usualDitail").hide();
}

function detail(id){
	currentData = dataList[id];
	clearForm();
	setForm(currentData);
	$("#operator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();
	$("#clueFollowDiv").show();
	$("#usualDitail").show();
	if(localStorage.getItem('isBusiManage')==='false'){
		$("#y_lingqu").hide();
	}else if(localStorage.getItem('isBusiManage')==='true'){
		$("#y_lingqu").show();
	}else{
		console.log('Exception')
	}
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		currentData = dataList[id];
		update(currentData);
	});
}


function deleteData(id){
	 if(confirm("确定删除该线索?")){
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/clue/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	var cur = $('.paginItem.current').find("a").html();
				cur = parseInt(cur);
				search(cur);
				alert(result.message);
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function getSearchParameter(currentPage){
	try{
		var parameter = $("INPUT[name='parameter']").val();	
		var provinceId = $("#searchProvince").val();
		var cityId = $("#searchCity").val();
		var spaceId = $("#searchSpace").val();
		if(provinceId == '0'){
			provinceId = '';
		}	
		if(cityId == '0'){
			cityId = '';
		}	
		if(spaceId == '0'){
			spaceId = '';
		}
		
		var visitTimeStart = $("INPUT[name='visitTimeStart']").val();
		var visitTimeEnd = $("INPUT[name='visitTimeEnd']").val();
		var requestJson = {currentPage:currentPage,data:{like:{"client.companyName":parameter,'client.memberName':parameter},equals:{'enable':true,'provinceId':provinceId,'cityId':cityId,'spaceId':spaceId,'visitTimeStart':visitTimeStart,'visitTimeEnd':visitTimeEnd}}};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}

function search(currentPage){
	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	$.ajax({
        url: '/euc/client/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		
        		var clientType = '';
        		var clientName = '';
        		if(data['client'] != null){
        			clientType = $.trim(data['client'].clientType);
        			if(clientType == '个人'){
        				clientName = $.trim(data['client'].memberName);
        			}else{
        				clientName = $.trim(data['client'].companyName);
        			}
        			if(clientName == ''){
        				clientName = $.trim(data['contact']);
        			}
        		}
        		
        		var spaceName = '';
        		if($.trim(data["spaceId"]) != '' && spaces != null){
        			spaceName =$.trim(spaces[data["spaceId"]].spaceName);
        		}
        		
        		var productTypeName = '';
        		if($.trim(data["productTypeId"]) != ''){
        			productTypeName =$.trim(productTypes[data["productTypeId"]].productTypeName);
        		}
        		
        		var sourceOfChannelName = '';
        		if($.trim(data["sourceChannelId"]) != ''){
        			sourceOfChannelName =$.trim(sourceOfChannels[data["sourceChannelId"]].sourceOfChannelName);
        		}
        		
        		var processPersonlName = '';
        		if(data.processPerson != null){
        			processPersonlName =$.trim(data.processPerson.name);
        		}
        		var bgcolor= localStorage.getItem('trcolor');
        		if(i % 2 == 0){
        			bgcolor = '';
        		}
        		var html = '<tr '+ bgcolor +'>';
        		html += '<td>' + clientName + '</td>';  
        		html += '<td>' + clientType + '</td>';        		      		
        		html += '<td>' + cities[data.cityId].cityName + '</td>';
        		html += '<td>' + spaceName + '</td>';
        		html += '<td>' + productTypeName + '</td>';
        		html += '<td>' + sourceOfChannelName + '</td>';
        		html += '<td>' + data.clientClissification + '</td>'; 
        		html += '<td>' + processPersonlName + '</td>';
        		html += '<td>' + $.trim(data.visitTime) + '</td>';
        		html += '<td>' + data.createTime + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteData('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log('/euc/client/query error');
        }
    });
}

